//
//  SideViewController.m
//  test
//
//  Created by apple on 14/12/11.
//
//

#import "SideViewController.h"
#import "CommonUtil.h"
//定义常量表示拉动方向
typedef NS_ENUM(NSUInteger, SliderMoveDirection) {
    SliderMoveDirectionNone = 0,
    SliderMoveDirectionLeft
};

@interface SideViewController (){
    UIView *_leftView;
    UIView *_mainView;
    SliderMoveDirection ShowViewDirection;//现在显示的界面
    CGFloat currentOffsetX;
    //侧滑的占界面宽的比例
    float ContentOffSet;
    //界面缩小的比例
    float ContentSizeRatio;
    //动画发生的条件的大小
    float ContentMinOffSet;
}

//左右视图拉出所用的时间
@property (assign, nonatomic) NSTimeInterval Duration;
//用以记录被当做主控制器展示主视图过的控制器
@property (strong, nonatomic) NSMutableDictionary *controllersDict;

//滑动手势
@property (strong,nonatomic) UIPanGestureRecognizer * pan;
//点击手势
@property (strong,nonatomic) UITapGestureRecognizer * tap;
@end

@implementation SideViewController

//制造反弹的动态效果，当通过按钮叫出导航栏时有效
static const CGFloat kOpenSpringDamping = 0.65f;
static const CGFloat kOpenSpringVelocity = 0.10f;

+ (SideViewController *)shareVc
{
    static SideViewController *sharedAccountManagerInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedAccountManagerInstance = [[self alloc] init];
    });
    return sharedAccountManagerInstance;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self _initValues];
    [self _initSubviews];
    [self addGesture];
}
- (void)_initValues{
    //界面初始时显示主页面
    ShowViewDirection = SliderMoveDirectionNone;
    //左右界面显示消失动画的时间
    self.Duration = 0.6f;
    //显示左右界面时主页面滑动占屏幕宽的比例
    ContentOffSet = 0.5 * [UIScreen mainScreen].bounds.size.width;
    //屏幕缩小比例
    ContentSizeRatio = 0.8;
    //动画发生的条件的大小
    ContentMinOffSet = 60;
    //mainViewControlle字典
    if (self.controllersDict == nil) {
        self.controllersDict = [[NSMutableDictionary alloc]init];
    }
    
    //主相对位移
    currentOffsetX = 0;
    
}
//- (void)setMainController:(UIViewController *)mainController{
//    _mainController = mainController;
//    if (self.controllersDict == nil) {
//        self.controllersDict = [[NSMutableDictionary alloc]init];
//    }
//    [self.controllersDict setObject:mainController forKey:@"SIMain"];
//}
- (void)_initSubviews{
    _leftView = [[UIView alloc] initWithFrame:self.view.bounds];
    
    _mainView = [[UIView alloc] initWithFrame:self.view.bounds];
    
    _leftController.view.bounds = _leftView.bounds;
    [_leftView addSubview:_leftController.view];
    [self addChildViewController:_leftController];
    [self.view insertSubview:_leftView atIndex:0];
    
    //主视图要最后添加（即添加到最上面显示）
    _mainController.view.bounds = _mainView.bounds;
    [_mainView addSubview:_mainController.view];
    [self addChildViewController:_mainController];
    [self.view addSubview:_mainView];
}
//展示左右视图和Main视图的动画
- (void)showLeftView{
    [self showSideWithController:SliderMoveDirectionLeft withDuration:self.Duration];
}
- (void)showMainView{
    [UIView beginAnimations:nil context:nil];
    _mainView.transform = CGAffineTransformScale(CGAffineTransformIdentity,1.0,1.0);
    _mainView.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2,[UIScreen mainScreen].bounds.size.height/2);
    [UIView commitAnimations];
}
//添加手势的方法
- (void)addGesture{
    //滑动手势
    _pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan:)];
//    [_mainView addGestureRecognizer:_pan];
//    UISwipeGestureRecognizer* recognizer;
//    recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
//    recognizer.direction = UISwipeGestureRecognizerDirectionLeft;
//    [self.view addGestureRecognizer:recognizer];
    
}
- (void)handleSwipeFrom:(UISwipeGestureRecognizer*)recognizer {
    [self showMainView];
    //    [self.view removeGestureRecognizer:recognizer];
}
- (void)mainViewAddPanGestures{
    if (_pan) {
        [_mainView removeGestureRecognizer:_pan];
        _pan = nil;
    }
    _pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan:)];
//    [_mainView addGestureRecognizer:_pan];
}
- (void)mainViewAddTapGestures{
    if (_tap) {
        [_mainView removeGestureRecognizer:_tap];
    }else{
        _tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handeTap:)];
        _tap.numberOfTapsRequired = 1;
        _tap.numberOfTouchesRequired = 1;
    }
    
    [_mainView addGestureRecognizer:_tap];
}
#pragma mark - side bar select delegate
- (void)changeMainViewController:(UIViewController *)controller
{
    
}
#pragma mark - 滑动手势

//滑动手势
- (void) handlePan: (UIPanGestureRecognizer *)recognizer{
    //视图宽度
    if (recognizer.state == UIGestureRecognizerStateChanged) {
        CGFloat translation = [recognizer translationInView:_mainView].x;
        
        if (translation+currentOffsetX <= ContentOffSet && translation+currentOffsetX >= 0) {
            float mscal = 0;  //主视图大小比例
            mscal = 1 - ((translation+currentOffsetX)/ContentOffSet)*(1 - ContentSizeRatio);
            CGAffineTransform mscale = CGAffineTransformMakeScale(mscal, mscal);
            CGAffineTransform mtranslation = CGAffineTransformMakeTranslation(translation+currentOffsetX, 0);
            CGAffineTransform mconcat = CGAffineTransformConcat(mscale, mtranslation);
            _mainView.transform = mconcat;
        }
    }else if (recognizer.state == UIGestureRecognizerStateEnded){
        currentOffsetX = _mainView.transform.tx;
        //分界速度，小于分界速度则返回原状态
        float velo = ABS([recognizer velocityInView:_mainView].x);
        float duration801 = ContentOffSet / velo;
        float duration799 = self.Duration;
        if (ShowViewDirection == SliderMoveDirectionNone) {
            if (fabs(currentOffsetX)< ContentMinOffSet) {
                if (velo > 800) {
                    [self showSideWithController:SliderMoveDirectionNone withDuration:duration801];
                }else{
                    [self showSideWithController:SliderMoveDirectionNone withDuration:duration799];
                }
                
            }else if(currentOffsetX>ContentMinOffSet)
            {
                if (velo > 800) {
                    [self showSideWithController:SliderMoveDirectionLeft withDuration:duration801];
                }else{
                    [self showSideWithController:SliderMoveDirectionLeft withDuration:duration799];
                }
            }
        }else if (ShowViewDirection == SliderMoveDirectionLeft){
            if (fabs(currentOffsetX)<ContentOffSet-ContentMinOffSet) {
                if (velo > 800) {
                    [self showSideWithController:SliderMoveDirectionNone withDuration:duration801];
                }else{
                    [self showSideWithController:SliderMoveDirectionNone withDuration:duration799];
                }
                
            }else if(currentOffsetX>ContentOffSet-ContentMinOffSet)
            {
                if (velo > 800) {
                    [self showSideWithController:SliderMoveDirectionLeft withDuration:duration801];
                }else{
                    [self showSideWithController:SliderMoveDirectionLeft withDuration:duration799];
                }
                
            }
        }
        
    }
    
}
#pragma mark - 单击手势
-(void) handeTap:(UITapGestureRecognizer *)tap{
    [self showSideWithController:SliderMoveDirectionNone withDuration:self.Duration];    
}
#pragma ShowAnimation Methods
- (void)showSideWithController:(SliderMoveDirection)sliderMoveDirection withDuration:(float)duration{
    void (^animations)(void) = ^{
        switch (sliderMoveDirection) {
            case SliderMoveDirectionNone:
            {
                CGAffineTransform mscale = CGAffineTransformMakeScale(1.0, 1.0);
                CGAffineTransform mtranslation = CGAffineTransformMakeTranslation(0, 0);
                CGAffineTransform mconcat = CGAffineTransformConcat(mscale, mtranslation);
                _mainView.transform = mconcat;
                
            }
                break;
            case SliderMoveDirectionLeft:
            {
                CGAffineTransform mscale = CGAffineTransformMakeScale(ContentSizeRatio, ContentSizeRatio);
                CGAffineTransform mtranslation = CGAffineTransformMakeTranslation(ContentOffSet, 0);
                CGAffineTransform mconcat = CGAffineTransformConcat(mscale, mtranslation);
                _mainView.transform = mconcat;
                
            }
                break;
            default:
                break;
        }
    };
    
    void (^complete)(BOOL) = ^(BOOL finished) {

        _mainView.userInteractionEnabled = YES;
        _leftView.userInteractionEnabled = YES;
        ShowViewDirection = sliderMoveDirection;
        if (sliderMoveDirection == SliderMoveDirectionNone) {
            if (_tap) {
                [_mainView removeGestureRecognizer:_tap];
                //                _tapGestureRecognizer = nil;
            }
            self.mainController.view.userInteractionEnabled = YES;
            
        }else{
            [self mainViewAddTapGestures];
            self.mainController.view.userInteractionEnabled = NO;
        }
        currentOffsetX = _mainView.transform.tx;
    };

    _mainView.userInteractionEnabled = NO;
    _leftView.userInteractionEnabled = NO;
    if (sliderMoveDirection == SliderMoveDirectionLeft) {
        [UIView animateWithDuration:self.Duration
                              delay:0
             usingSpringWithDamping:kOpenSpringDamping  //弹性效果
              initialSpringVelocity:kOpenSpringVelocity
                            options:UIViewAnimationOptionCurveLinear
                         animations:animations
                         completion:complete];
    }else if (sliderMoveDirection == SliderMoveDirectionNone) {
        [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:animations completion:complete];
//        [UIView animateWithDuration:duration animations:animations completion:complete];
    }
}

- (void)showContentViewWithModel:(NSString *)className withSb:(NSString *)sbName
{
//    [self _closeSliderNavigation];//test
    UIViewController *controller = [self.controllersDict objectForKey:className];
    if (controller == nil) {
        controller = [CommonUtil getVCWithSbIden:sbName identify:className];
        if (controller) {
            [self.controllersDict setObject:controller forKey:className];
            //如果当前已经有视图被显示，则将其取消
            if (_mainView.subviews.count > 0) {
                [[_mainView.subviews firstObject] removeFromSuperview];
            }
            
            controller.view.frame = _mainView.bounds;
            [_mainView addSubview:controller.view];
            
            self.mainController = controller;
        }else{
            NSLog(@"Warning, This ViewController is nil");
        }
        
    }else{
        //如果当前已经有视图被显示，则将其取消
        if (_mainView.subviews.count > 0) {
            [[_mainView.subviews firstObject] removeFromSuperview];
        }
        controller.view.frame = _mainView.bounds;
        [self addChildViewController:controller];
        [_mainView addSubview:controller.view];
        self.mainController = controller;
        
        
    }
    
    [self showSideWithController:SliderMoveDirectionNone withDuration:self.Duration];
    
}
#pragma mark - nav con delegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    
}
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if ([navigationController.viewControllers count]>1) {
        [self removepanGestureReconginzerWhileNavConPushed:YES];
    }else
    {
        [self removepanGestureReconginzerWhileNavConPushed:NO];
    }
    
}

- (void)removepanGestureReconginzerWhileNavConPushed:(BOOL)push
{
    if (push) {
        if (_pan) {
            [_mainView removeGestureRecognizer:_pan];
            _pan = nil;
        }
        if (_tap) {
            [_mainView removeGestureRecognizer:_tap];
            _tap = nil;
        }
    }else
    {
        
        if (!_pan) {
            [self mainViewAddPanGestures];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//#warning 为了界面美观，所以隐藏了状态栏。如果需要显示则去掉此代码
//- (BOOL)prefersStatusBarHidden
//{
//    return YES; //返回NO表示要显示，返回YES将hiden
//}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
